package com.qf.mxapp.util;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.CompletableFuture;

/**
 * @author xy
 * 阿里云短信发送工具类
 */
@Component
public class SendSms {

    @Value("${alibaba.accessKeyId}")
    private  String accessKeyId;

    @Value("${alibaba.accessKeySecret}")
    private  String accessKeySecret;

    @Value("${sms.signName}")
    private  String signName;

    @Value("${sms.templateCode}")
    private  String templateCode;

    public  String sendCode(String tel) throws Exception {
    // 添加用户信息
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
                .build());

        // 配置本地客户端
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                               .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build();

        //随机生成一个6位数的验证码（数字）
        Random random = new Random();
        String code = Integer.toString(100000 + random.nextInt(90000));
        System.out.println(code);
        //构造验证码JSON格式
        HashMap<String, String> map_code = new HashMap<>();
        map_code.put("code", code);
        String code_json = new Gson().toJson(map_code);

        //设置请求中的参数信息
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(tel)
                .signName(signName)
                .templateCode(templateCode)
                .templateParam(code_json)//自己在后台随机生成的验证码，也是发送到手机上的验证码，格式必须是JSON格式
                .build();

        // 使用客户发送请求
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // 获取请求响应的数据
        SendSmsResponse resp = response.get();
        //将请求响应数据转换成josn数据模式
        String res_code = resp.getBody().getCode();
        System.out.println(new Gson().toJson(resp));
        //判断本次操作是否成功
        if (res_code.equalsIgnoreCase("OK")){
            // 关闭客户端
            client.close();
            return code;
        }else {
            // 关闭客户端
            client.close();
            return null;
        }
    }

}
